# utils/pagination.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger, Page

from conf.my_settings import PAGINATION_SETTINGS

class CustomPaginator:
    def __init__(self, queryset, page_size=None):
        self.page_size = page_size or PAGINATION_SETTINGS.get("PAGE_SIZE", 10)
        self.paginator = Paginator(queryset, self.page_size)
        self.paginated_data = None

    def get_page(self, page_number=None, offset=0):
        page_number = page_number or (int(offset) // self.page_size) + 1
        try:# 使用page方式来获取结果
            self.paginated_data = self.paginator.page(page_number)
        except PageNotAnInteger:# 如果页码不是一个整数，则返回第一页
            self.paginated_data = self.paginator.page(1)
        except EmptyPage:# 如果页码超过范围，则返回最后一页
            self.paginated_data = self.paginator.page(self.paginator.num_pages)
        return self.paginated_data

    def paged_data(self, serializer, data_name="datas"):
        return {
            "total": self.paginated_data.paginator.num_pages,
            "hasPrev": self.paginated_data.has_previous(),
            "curPage": self.paginated_data.number,
            "hasNext": self.paginated_data.has_next(),
            data_name: serializer(self.paginated_data.object_list, many=True).data
        }